﻿using System;
using fastCSharp;
using System.Net;
using System.Collections.Generic;
using System.Reflection;

namespace OnlineJudge
{
    public static class ServerIp
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        static string ipString(uint ip)
        {
            return ((byte)ip).toString() + "." + ((byte)(ip >> 8)).toString() + "." + ((byte)(ip >> 16)).toString() + "." + ((byte)(ip >> 24)).toString();
        }
        /// <summary>
        /// 自动获取局域网IP地址
        /// </summary>
        /// <param name="serverType"></param>
        /// <param name="serverName"></param>
        /// <returns></returns>
        public static fastCSharp.code.cSharp.tcpServer GetTcpServer(Type serverType, string serverName)
        {
            fastCSharp.code.cSharp.tcpServer tcpRegisterAttribute = fastCSharp.code.cSharp.tcpServer.GetConfig("tcpRegister", typeof(fastCSharp.net.tcp.tcpRegister));
            fastCSharp.code.cSharp.tcpServer ojAttribute = fastCSharp.code.cSharp.tcpServer.GetConfig(serverName, serverType);
            if (tcpRegisterAttribute.Host == null || ojAttribute.Host == null)
            {
                uint currentIp = 0, localIp = 192 + (168 << 8);
                foreach (IPAddress ip in Dns.GetHostAddresses(Dns.GetHostName()))
                {
                    if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                    {
                        uint ipv4 = (uint)ip.Address;
                        if ((ipv4 & 0xffff) == localIp)
                        {
                            if ((ipv4 & currentIp) == currentIp) currentIp = ipv4;
                        }
                    }
                }
                if (currentIp != 0)
                {
                    if (tcpRegisterAttribute.Host == null)
                    {
                        tcpRegisterAttribute.Host = ipString((currentIp & 0xffffff) + 0x1000000);
                        Dictionary<hashString, subString> configs = (Dictionary<hashString, subString>)typeof(fastCSharp.config.pub).GetField("configs", BindingFlags.Static | BindingFlags.NonPublic).GetValue(null);
                        if (configs == null)
                        {
                            typeof(fastCSharp.config.pub).GetField("configs", BindingFlags.Static | BindingFlags.NonPublic).SetValue(null, configs = new Dictionary<hashString, subString>());
                        }
                        tcpRegisterAttribute.VerifyMethodType = null;
                        configs["code.cSharp.tcpServer.tcpRegister"] = fastCSharp.emit.jsonSerializer.ObjectToJson(tcpRegisterAttribute);
                    }
                    if (ojAttribute.Host == null) ojAttribute.Host = ipString(currentIp);
                }
            }
            return ojAttribute;
        }
    }
}
